<template>
  <div class="my-collects-page">
    <!-- 顶部导航栏 -->
    <Navbar />

    <div class="container">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>我的收藏</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="content">
        <h2 class="page-title">我的收藏</h2>

        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索收藏的商品"
            clearable
            style="max-width: 400px"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>

        <!-- 收藏列表 -->
        <div class="collect-list" v-loading="loading">
          <el-empty 
            v-if="!loading && collectList.length === 0" 
            description="暂无收藏商品"
            :image-size="200"
          >
            <el-button type="primary" @click="goToHome">去逛逛</el-button>
          </el-empty>

          <div v-else class="goods-grid">
            <el-card
              v-for="item in collectList"
              :key="item.id"
              class="goods-card"
              :body-style="{ padding: '0px' }"
              shadow="hover"
            >
              <div class="card-content">
                <img 
                  :src="getImageUrl(item.picture)" 
                  class="goods-image"
                  @click="goToDetail(item.goodsId)"
                />
                <div class="goods-info">
                  <h3 class="goods-name" @click="goToDetail(item.goodsId)">
                    {{ item.goodsName }}
                  </h3>
                  <p class="goods-desc">{{ item.desc }}</p>
                  <div class="goods-footer">
                    <div class="price-stock">
                      <span class="goods-price">¥{{ item.price }}</span>
                      <span class="goods-stock">库存: {{ item.stock }}</span>
                    </div>
                    <div class="actions">
                      <el-button 
                        type="danger" 
                        text
                        :icon="Delete"
                        @click="handleRemoveCollect(item)"
                      >
                        取消收藏
                      </el-button>
                      <el-button
                        type="primary"
                        size="small"
                        @click="goToDetail(item.goodsId)"
                      >
                        查看详情
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 分页 -->
        <el-pagination
          v-if="total > 0"
          class="pagination"
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadCollects"
          @current-change="loadCollects"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getMyCollects, toggleCollect } from '@/api/collect'
import { getFileUrl } from '@/api/file'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Delete } from '@element-plus/icons-vue'
import Navbar from '@/components/Navbar.vue'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const collectList = ref([])
const searchKeyword = ref('')
const pageNum = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 加载收藏列表
const loadCollects = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }

    if (searchKeyword.value.trim()) {
      params.goodsName = searchKeyword.value.trim()
    }

    const data = await getMyCollects(params)
    collectList.value = data.list || []
    total.value = data.total || 0
  } catch (error) {
    console.error('获取收藏列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pageNum.value = 1
  loadCollects()
}

// 取消收藏
const handleRemoveCollect = async (item) => {
  try {
    await ElMessageBox.confirm('确定要取消收藏吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await toggleCollect(item.goodsId)
    ElMessage.success('已取消收藏')
    loadCollects()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消收藏失败:', error)
    }
  }
}

// 跳转到商品详情
const goToDetail = (goodsId) => {
  router.push(`/goods/${goodsId}`)
}

// 回到首页
const goToHome = () => {
  router.push('/')
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  return getFileUrl(imagePath)
}

onMounted(() => {
  // 检查是否登录
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/')
    return
  }
  loadCollects()
})
</script>

<style scoped>
.my-collects-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding-top: 20px;
}

.content {
  background: white;
  border-radius: 8px;
  padding: 30px;
  min-height: 500px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 20px 0;
  color: #333;
}

.search-bar {
  margin-bottom: 30px;
}

.collect-list {
  min-height: 300px;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.goods-card {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
}

.goods-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  flex-direction: column;
}

.goods-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  cursor: pointer;
}

.goods-info {
  padding: 15px;
}

.goods-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
  transition: color 0.3s;
}

.goods-name:hover {
  color: #409eff;
}

.goods-desc {
  font-size: 14px;
  color: #999;
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-footer {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.price-stock {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-price {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.goods-stock {
  font-size: 13px;
  color: #999;
}

.actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .goods-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 15px;
  }

  .goods-image {
    height: 150px;
  }

  .content {
    padding: 20px;
  }
}
</style>
